<script lang="ts" setup>
import {onActivated, onBeforeUnmount, onDeactivated, onMounted, reactive, ref} from "vue";
import {service, fileIcon} from "@/utils";
import {getRunLogContent, getRunLogDir} from '@/api/system'
import CodeMirror from "@/components/codemirror/index.vue";
import store from "@/store";

const {application} = store.globalStore;

const treeRef = ref();
const visible = ref(false);
const content = ref('');
const suspend = ref(false);
const disabled = ref(true);
const moduleData = ref<any[]>([{label: 'AdminApplication',  options: [{label: '后台管理平台系统', value: ' '}]}]);

const dataForm = reactive({
    uri: ' ',
    lines: 500,
    second: 5,
});

let timer: any = null;
const theme = {
    '.cm-line': {
        lineHeight: '28px',
    },
    '.cm-scroller': {
        fontSize: '15px',
        overflow: 'auto'
    },
}
const properties = reactive({
    treeProps: {
        label: 'name',
        isLeaf: 'leaf',
    },
    handle: {
        start: (refresh?: boolean) => {
            if (refresh) getRunLogContent(dataForm, content);
            if (!suspend.value) {
                timer = setInterval(() => getRunLogContent(dataForm, content), dataForm.second * 1000);
            }
        },
        stop: () => {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        },
        suspend: () => {
            suspend.value = !suspend.value;
            if (suspend.value) {
                properties.handle.stop();
            } else {
                properties.handle.start(true);
            }
        },
        change: (refresh: boolean) => {
            properties.handle.stop();
            properties.handle.start(refresh);
        },
        checkChange: () => {
            disabled.value = treeRef.value.getCheckedKeys().length === 0
        },
        loadNode: (node: any, resolve: (value: any) =>void) => {
            if (node.level === 0) {
                getRunLogDir(dataForm.uri).then(({data}) => resolve(data));
            } else {
                getRunLogDir(dataForm.uri, node.data.path).then(({data}) => resolve(data))
            }
        },
        download: () => {
            const items = treeRef.value.getCheckedKeys();
            service.download('/log/download', {paths: items.join(','), uri: dataForm.uri}).then(() => {
                treeRef.value.setCheckedKeys([], false);
            }).catch(e => {
                console.error(e)
            })
        }
    }
})

// 挂载前请求模块数据
// onBeforeMount(() => {
//     getModuleListByStatus([1, 2]).then(({data}) => {
//         let temp = {} as {[key:string]:any}
//         data.forEach((item:any) => {
//             if (!Object.prototype.hasOwnProperty.call(temp, item.name)) {
//                 temp[item.name] = {label: item.name, options: []};
//             }
//             temp[item.name].options.push({label: item.title, value: item.uri})
//         })
//         moduleData.value.push(...Object.values(temp));
//     })
// })

// 挂载完后启动定时任务请求日志信息
onMounted(() => properties.handle.start())

// 卸载前停止定时任务
onBeforeUnmount(() => properties.handle.stop());

onActivated(() => {
    suspend.value = false;
    properties.handle.start();
})

onDeactivated(() => {
    suspend.value = true;
    properties.handle.stop();
})
</script>
<template>
    <el-form :model="dataForm" inline>
        <!--<el-form-item label="应用程序" prop="uri">
            <el-select v-model="dataForm.uri" style="width: 220px;" @change="properties.handle.change(true)">
                <el-option-group v-for="group in moduleData" :key="group.label" :label="group.label">
                    <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
                        <span style="float: left">{{ item.label }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px; padding-left: 100px">{{ item.value }}</span>
                    </el-option>
                </el-option-group>
            </el-select>
        </el-form-item>-->
        <el-form-item label="显示行数" prop="lines">
            <el-input-number v-model="dataForm.lines" :step="10" style="width: 120px"></el-input-number>
        </el-form-item>
        <el-form-item label="刷新时间（秒）" prop="second">
            <el-input-number v-model="dataForm.second" :min="3" style="width: 120px" @change="properties.handle.change(false)"></el-input-number>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="properties.handle.suspend()">{{ !suspend ? '暂停' : '继续' }}</el-button>
            <el-button type="primary" @click="() => visible = true">日志目录</el-button>
        </el-form-item>
    </el-form>
    <code-mirror v-model="content" :theme="theme" :scrollbar-at-bottom="true" style="height: calc(100% - 42px)" :dark="application.dark"/>
    <el-dialog v-model="visible" append-to-body destroy-on-close title="下载运行日志" width="450">
        <el-scrollbar height="40vh">
            <el-tree ref="treeRef"
                     :accordion="true"
                     :check-strictly="true"
                     :lazy="true"
                     :load="properties.handle.loadNode"
                     :props="properties.treeProps"
                     :show-checkbox="true"
                     node-key="path"
                     @check-change="properties.handle.checkChange()">
                <template #default="{ node, data }">
                    <el-image :src="fileIcon(data.extension)" style="position: relative;float: left; height: 18px;"></el-image>
                    <span>{{ node.label }}</span>
                </template>
            </el-tree>
        </el-scrollbar>
        <template #footer>
            <el-button :disabled="disabled" icon="download" @click="properties.handle.download()">下载</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-form-item--default {
    margin: 5px;
}
</style>